<template>
  <div id="home" v-loading="isLoading">
    <el-drawer class="record-panel" title="请假记录" direction="ltr" size="100%" :visible.sync="isShowRecordPanel">
      <el-timeline>
        <el-timeline-item v-for="(record, idx) in recordData" :key="idx"
                          :timestamp="record.add_time">
          <div class="image-con" style="display: flex;flex-direction: row;justify-content: space-around;">
            <el-image style="width: 30%; height: auto;"
                      :preview-src-list="[record.image_tip, record.image_record]"
                      :src="record.image_tip"/>
            <el-image style="width: 30%; height: auto;"
                      :preview-src-list="[record.image_tip, record.image_record]"
                      :src="record.image_record"/>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>

    <div class="main-container">
      <el-menu :default-active="activeIdx" mode="horizontal" @select="handleSelect">
        <el-menu-item index="1">多人请假</el-menu-item>
        <el-menu-item index="2">群组请假</el-menu-item>
      </el-menu>
      <div class="line"></div>
      <div class="panel">

        <div class="student-table-con" v-show="activeIdx === '1'" :key="1">
          <div class="control-group" style="padding: 12px;">
            <el-form>
              <el-form-item>
                <el-button type="warning"
                           @click="handleAskForLeave([], 0)">【默认组】 一键请假
                </el-button>
                <el-button type="primary" :disabled="multipleStudentSelection.length <= 0"
                           @click="handleAskForLeave(multipleStudentSelection, 1)">请假
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-input clearable placeholder="输入检索关键字（学号）"
                          v-model="studentTableForm.search"/>
              </el-form-item>
            </el-form>
          </div>
          <el-table :data="studentData" style="width: 100%;height: calc(100vh - 300px);overflow-y: auto"
                    @selection-change="handleStudentSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="name" align="center" label="姓名"/>
            <el-table-column prop="username" align="center" label="学号"/>
            <el-table-column prop="areaStr" align="center" label="地区"/>
            <el-table-column prop="mobile" align="center" label="手机号"/>
            <el-table-column prop="mobile_spe" align="center" label="备用手机号"/>
            <el-table-column prop="target" align="center" label="目的地"/>
            <el-table-column prop="reasonStr" align="center" label="原因"/>
            <el-table-column prop="nextStr" align="center" label="下一步"/>
            <el-table-column label="操作" align="center" width="250px">
              <template slot-scope="scope">
                <el-button type="primary" @click="handleAskForLeave(scope.row, 1)">请假</el-button>
                <el-button type="warning" @click="handleListRecord(scope.row)">查看记录</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination layout="total, prev, pager, next, jumper"
                         style="margin-top: 12px;"
                         :current-page="studentTableForm.page"
                         :total="studentTableForm.count"
                         :page-size="10"
                         @current-change="handleStudentTablePageChanged"/>
        </div>

        <div class="group-table-con" v-show="activeIdx === '2'" :key="2">
          <div class="control-group" style="padding: 12px">
            <el-form>
              <el-form-item>
                <el-button type="warning"
                           @click="handleAskForLeave([], 0)">【默认组】 一键请假
                </el-button>
                <el-button type="primary" :disabled="multipleGroupSelection.length <= 0"
                           @click="handleAskForLeave(multipleGroupSelection, 2)">
                  请假
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-input clearable placeholder="输入检索关键字（群名称）"
                          v-model="groupTableForm.search"/>
              </el-form-item>
            </el-form>
          </div>
          <el-table :data="groupData" style="width: 100%;height: calc(100vh - 300px);overflow-y: auto"
                    @selection-change="handleGroupSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="name" align="center" label="群组名"/>
            <el-table-column label="操作" align="center" width="350">
              <template slot-scope="scope">
                <el-button type="primary" @click="handleAskForLeave(scope.row, 2)">请假</el-button>
                <el-button v-if="scope.row.is_default" type="warning" @click="handleSetDefaultGroup(scope.row, 0)">
                  取消默认组
                </el-button>
                <el-button v-else type="danger" @click="handleSetDefaultGroup(scope.row, 1)">设置默认组</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination layout="total, prev, pager, next, jumper"
                         style="margin-top: 12px;"
                         :current-page="groupTableForm.page"
                         :total="groupTableForm.count"
                         :page-size="10"
                         @current-change="handleGroupTablePageChanged"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import api from '@/api'

export default {
  name: "Home",
  data() {
    return {
      // loading flag
      isLoading: false,
      // 是否 record panel
      isShowRecordPanel: false,
      // 导航栏激活 idx
      activeIdx: '1',
      // 记录数据
      recordData: [],
      // 学生数据
      studentData: [],
      // 群组数据
      groupData: [],
      // 学生表单
      studentTableForm: {
        page: 1,
        count: 0,
        search: ''
      },
      // 群组表单
      groupTableForm: {
        page: 1,
        count: 0,
        search: ''
      },
      // 表格中选中的学生
      multipleStudentSelection: [],
      // 表格中选中的群组
      multipleGroupSelection: [],
    }
  },
  watch: {
    activeIdx: {
      handler(val) {
        switch (val) {
          case '1':
            this.loadStudentInfo()
            break
          case '2':
            this.loadStudentGroup()
            break
        }
      },
      deep: true
    },
    studentTableForm: {
      handler() {
        this.loadStudentInfoDebounce()
      },
      deep: true
    },
    groupTableForm: {
      handler() {
        this.loadStudentGroupDebounce()
      },
      deep: true
    }
  },
  methods: {
    // 查看记录
    handleListRecord(data) {
      if (!data) {
        return -1
      }

      this.isLoading = true
      this.recordData = []
      // load record list
      api.loadAllRecord({student__id: data.id})
          .then(({data}) => {
            this.isLoading = false
            this.isShowRecordPanel = true
            this.recordData = data
          })
          .catch(() => {
            this.isLoading = false
          })
    },
    // 激活选中的导航菜单
    handleSelect(idx) {
      this.activeIdx = idx
    },
    // 加载学生数据
    loadStudentInfoDebounce: _.debounce(function () {
      this.loadStudentInfo()
    }, 500),
    loadStudentInfo() {
      const form = {...this.studentTableForm}
      delete form.results
      api.loadAllStudentInfo(this.studentTableForm)
          .then(({data}) => {
            this.studentTableForm.count = data.count
            this.studentData = data.results
            this.studentData.forEach(item => {
              switch (item.reason) {
                case 0:
                  item.reasonStr = '回家'
                  break
                case 1:
                  item.reasonStr = '实习'
                  break
                case 2:
                  item.reasonStr = '其他'
                  break
              }

              switch (item.area) {
                case 0:
                  item.areaStr = '临港'
                  break
                case 1:
                  item.areaStr = '闵行'
                  break
              }

              switch (item.next) {
                case 0:
                  item.nextStr = '办结'
                  break
                case 1:
                  item.nextStr = '送辅导员审核'
                  break
              }
            })
          })
    },
    // 加载群组
    loadStudentGroupDebounce: _.debounce(function () {
      this.loadStudentGroup()
    }, 500),
    loadStudentGroup() {
      const form = {...this.studentTableForm}
      delete form.results
      api.loadAllStudentGroup(this.groupTableForm)
          .then(({data}) => {
            this.groupData = data.results
            this.groupTableForm.count = data.count
            data.results.forEach(item => {
              if (item.is_default) {
                item.name = '【默认组】' + item.name
              }
            })
          })
    },
    // 表格选中学生
    handleStudentSelectionChange(val) {
      this.multipleStudentSelection = val
    },
    // 表格选中群组
    handleGroupSelectionChange(val) {
      this.multipleGroupSelection = val
    },
    // 处理默认群组请假
    handleAskForLeaveDefault() {
      this.$confirm('是否开始办理临时离校申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        alert('请假')
      })
    },
    // 设置默认分组
    handleSetDefaultGroup(data, type) {
      this.$confirm(type === 1 ? '是否设置为默认分组？' : '是否取消默认分组', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        api.setDefaultGroup({type, id: data.id})
            .then(res => {
              this.$message.success(type === 1 ? '设置成功!' : '取消设置成功!')
              this.loadStudentGroup()
            })
      })
    },
    handleGetRecord(data) {
      if (data === undefined || data === null) {
        return -1
      }


    },
    // 处理学生请假
    handleAskForLeave(data, type) {
      if (data === undefined || data === null || type === undefined || type === null) {
        return -1
      }

      this.$confirm('是否开始办理临时离校申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        let ids = Array.isArray(data) ? data.map(item => item.id) : [data.id];
        api.askForLeave({type, ids})
            .then(res => {
              this.$message.success('申请已提交！')
            })
      })
    },
    // 处理删除选中学生
    handleDeleteStudent(data) {
      this.$confirm('是否删除选中的学生信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        alert('请假')
        let ids = Array.isArray(data) ? data.map(item => item.id) : [data.id]
        // todo 删除
      })
    },
    // 处理删除选中群组
    handleDeleteGroup(data) {
      this.$confirm('是否删除选中的群组信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        alert('请假')
        let ids = Array.isArray(data) ? data.map(item => item.id) : [data.id]
        // todo 删除
      })
    },
    // 处理分页器换页
    handleStudentTablePageChanged(page) {
      this.studentTableForm.page = page
    },
    handleGroupTablePageChanged(page) {
      this.groupTableForm.page = page
    }
  },
  created() {
    this.loadStudentInfo()
  }
}
</script>

<style scoped lang="scss">
#home {
  * {
    user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -webkit-user-select: none;
  }

  .main-container {
    padding: 18px;
    min-height: 100vh;
  }
}
</style>